package com.archive.forum.controller;

import com.archive.forum.dto.PaginationDTO;
import com.archive.forum.exception.CustomizeException;
import com.archive.forum.exception.ExceptionEnum;
import com.archive.forum.mapper.UserMapper;
import com.archive.forum.model.User;
import com.archive.forum.service.CommentService;
import com.archive.forum.service.PostService;
import com.archive.forum.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Objects;

@Controller
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private PostService postService;
    @Autowired
    private CommentService commentService;
    @GetMapping("/user/{id}/{action}")
    public String user(@PathVariable(name = "id") Integer id, @PathVariable(name = "action") String action,
                       @RequestParam(name = "page",defaultValue = "1") Integer page, @RequestParam(name = "size",defaultValue = "5") Integer size,
                       Model model, HttpServletRequest request){
        User logUser =  (User) request.getSession().getAttribute("user");
        User user =userMapper.selectByPrimaryKey(id);
        if(user==null){
            //用户不存在
            throw new CustomizeException(ExceptionEnum.USER_NOT_FOUND);
        }

        if(logUser!=null && logUser.getId().equals(user.getId())) {
            //用户查看自己主页
            switch (action) {
                case "index" ->{
                    //个人主页
                    model.addAttribute("section", "index");
                    model.addAttribute("sectionName", "我的主页");
                }
                case "setting" ->{
                    //个人设置
                    model.addAttribute("section", "setting");
                    model.addAttribute("sectionName", "我的设置");
                    model.addAttribute("description",user.getBio());
                }
                case "account" ->{
                    //个人账户
                    model.addAttribute("section", "account");
                    model.addAttribute("sectionName", "我的账户");
                }

            }

        }else {
            //用户查看他人页面
            switch (action) {
                case "index" ->{
                    model.addAttribute("section", "index");
                    model.addAttribute("sectionName",user.getNickname()+"的主页");
                }
                case "post" ->{
                    PaginationDTO paginationDTO= postService.listByUser(user.getId(),page,size);
                    model.addAttribute("paginationDTO",paginationDTO);
                    model.addAttribute("section", "post");
                    model.addAttribute("sectionName",user.getNickname()+"的帖子");
                }
                case "comment" ->{
                    PaginationDTO paginationDTO= commentService.list(user.getId(),page,size);
                    model.addAttribute("paginationDTO",paginationDTO);
                    model.addAttribute("section", "comment");
                    model.addAttribute("sectionName",user.getNickname()+"的评论");
                }
                case "setting", "account" ->{
                    throw new CustomizeException(ExceptionEnum.USER_FAIL);
                }
            }
        }
        model.addAttribute("user",user);

        return "user";
    }
    @GetMapping("/user/{path}")
    public String userPathHandler(
            @PathVariable(name = "path") String path,
            HttpServletRequest request) {

        // 尝试将路径解析为数字ID
        try {
            Integer id = Integer.parseInt(path);
            // 如果是数字，跳转到用户index页面
            return "redirect:/user/" + id + "/index";
        } catch (NumberFormatException e) {
            // 如果不是数字，获取当前登录用户
            User logUser = (User) request.getSession().getAttribute("user");
            if (logUser == null) {
                // 未登录用户访问非数字路径，重定向到登录或首页
                return "redirect:/login";
            }

            // 已登录用户，跳转到自己的对应页面
            return switch (path) {
                case "setting" -> "redirect:/user/" + logUser.getId() + "/setting";
                case "account" -> "redirect:/user/" + logUser.getId() + "/account";
                case "index" -> "redirect:/user/" + logUser.getId() + "/index";
                default -> throw new CustomizeException(ExceptionEnum.UNDEFINE_ERROR);
            };
        }
    }
    @PostMapping("/account")
    public String account(@RequestParam(name = "name",required = false) String name,
                          @RequestParam(name = "password",required = false) String password,
                          @RequestParam(name = "newPass", required = false)String newPass ,
                          @RequestParam(name = "newName", required = false)String newName,
                          HttpServletRequest request, Model model){
        model.addAttribute("section", "account");
        model.addAttribute("sectionName", "我的账户");
        User accountUser = (User) request.getSession().getAttribute("user");
        if (accountUser == null) {
            model.addAttribute("error", "请先登录");
            return "redirect:/login";
        }
        model.addAttribute("user", accountUser);
        if (name == null || name.isEmpty()|| password == null || password.isEmpty()) {
            model.addAttribute("error", "请填写完整信息");
            return "user";
        }

        User user = new User();
        user.setName(name);
        user.setPassword(userService.sha1(password));
        if(!Objects.equals(newPass, "")){
            newPass = userService.sha1(newPass);
        }
        return userService.account(user,accountUser,newPass,newName,model);
    }
    @PostMapping("/updateNickname")
    public String updateNickname(@RequestParam("userId") Integer userId,
                                 @RequestParam("newNickname") String newNickname,
                                 HttpServletRequest request, Model model) {
        model.addAttribute("section", "setting");
        model.addAttribute("sectionName", "我的设置");

        User accountUser = (User) request.getSession().getAttribute("user");
        if (accountUser == null) {
            model.addAttribute("error", "请先登录");
            return "redirect:/login";
        }

        User user = userMapper.selectByPrimaryKey(userId);
        if (user == null) {
            model.addAttribute("error", "用户不存在");
            return "user";
        }
        model.addAttribute("user", user);
        model.addAttribute("description", user.getBio()); // 保持简介内容不变
        if(newNickname==null|| Objects.equals(newNickname, "")){
            model.addAttribute("error", "不能设置空昵称");
            return "user";
        }
        user.setNickname(newNickname);
        userMapper.updateByPrimaryKeySelective(user);



        model.addAttribute("success", "昵称更新成功");
        return "user";
    }
    @PostMapping("/updateBio")
    public String updateBio(@RequestParam("userId") Integer userId,
                            @RequestParam("newBio") String newBio,
                            HttpServletRequest request, Model model) {
        model.addAttribute("section", "setting");
        model.addAttribute("sectionName", "我的设置");

        User accountUser = (User) request.getSession().getAttribute("user");
        if (accountUser == null) {
            model.addAttribute("error", "请先登录");
            return "redirect:/login";
        }

        User user = userMapper.selectByPrimaryKey(userId);
        if (user == null) {
            model.addAttribute("error", "用户不存在");
            return "user";
        }

        user.setBio(newBio);
        userMapper.updateByPrimaryKeySelective(user);

        model.addAttribute("user", user);
        model.addAttribute("description", user.getBio());
        model.addAttribute("success", "简介更新成功");
        return "user";
    }
}
